import { isString } from 'lodash-es'

import { useGlobalSetting } from '@/settings/system'
import { userStore } from '@/store/modules'
import {
  checkTmpSubscriptionStatus,
  openMiniAppHelper,
  requestTmpSubscriptionShow,
  toPromise
} from '@/utils'

import { showModal, showToast } from './uniHelper'

export async function handleMenuClick(item: MenuItem | null) {
  if (!item) return
  if (!item.type || !isString(item.url))
    return showToast('功能开发中，敬请期待')

  let rs
  const { appId, path, envVersion, queryData, extraData } =
    item.moreParams ?? {}

  switch (item.type) {
    case 'page':
      uni.navigateTo({
        url: item.url
      })
      break
    case 'tabbar':
      uni.switchTab({
        url: item.url
      })
      break
    case 'webview':
      uni.navigateTo({
        url: `/pages/webview/index?url=${item.url}`
      })
      break
    case 'openFile':
      uni.showLoading({ title: '数据加载中...' })
      try {
        rs = await toPromise(uni.downloadFile, { url: item.url, timeout: 30 })
        if (/^2\d+/.test(`${rs.statusCode}`)) {
          uni.openDocument({
            filePath: rs.tempFilePath
          })
        }
        throw new Error('文件下载失败')
      } catch (e) {
        return showModal((e as Error).message)
      } finally {
        uni.hideLoading()
      }
      break
    case 'miniApp':
      registerMiniAppBackCallback()
      openMiniAppHelper(
        { queryData, extraData },
        { path: item.url || path, appId: appId, envVersion }
      )
      break
    case 'link':
      uni.setClipboardData({
        data: item.url,
        success: () => {
          uni.hideToast()
          return showToast('链接已复制')
        }
      })
      break
    case 'subscribe':
      if (
        (item.url &&
          (await checkTmpSubscriptionStatus(item.url)).some((o) => o)) ||
        (useGlobalSetting().tmpIds.length &&
          !(await checkTmpSubscriptionStatus(useGlobalSetting().tmpIds)).some(
            (o) => !o
          ))
      ) {
        return showToast('消息已订阅，请勿重复点击订阅。')
      } else {
        await requestTmpSubscriptionShow(
          item.url ? [item.url] : useGlobalSetting().tmpIds
        )
      }

      requestTmpSubscriptionShow(
        item.url ? [item.url] : useGlobalSetting().tmpIds
      ).then(() => {
        showToast('消息订阅成功！')
      })
      break
    default:
      break
  }
}

function registerMiniAppBackCallback(cb?: Fn) {
  // 注册回调
  const callback: UniApp.OnAppShowCallback = async ({
    referrerInfo,
    scene
  }) => {
    if (referrerInfo?.extraData?.success) {
      await userStore.Login({ loginType: 2 })
      await showToast('实名认证成功！')
    }
    if (scene === 1038) {
      uni.offAppShow(callback as never)
      cb?.()
    }
  }
  uni.onAppShow(callback)
}
